﻿//===================================================================
//
// Description: Sparqube Picture Column Lite for SharePoint 2010
// Web: http://www.sparqube.com/
//
//-------------------------------------------------------------------
//
// Copyright (C) 2012 ArtfulBits.CZ (development[at]artfulbits.cz)
// Web: http://www.artfulbits.cz/
//
//-------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A 
// PARTICULAR PURPOSE.
//===================================================================

using System;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Sparqube.SharePoint.PictureColumnLite
{
	public partial class PictureLiteFieldContent :
		UserControl,
		IPostBackEventHandler
	{
		#region Fields

		private PictureLiteField m_fieldPicture = null;
		private PictureLiteValue m_originalValue = null;
		private PictureLiteValue m_value = null;

		#endregion //Fields

		#region Properties

		public PictureLiteField PictureField
		{
			get
			{
				return m_fieldPicture;
			}
			set
			{
				m_fieldPicture = value;
			}
		}

		public PictureLiteValue OriginalValue
		{
			get
			{
				return m_originalValue;
			}
			set
			{
				m_originalValue = value;
			}
		}

		public PictureLiteValue Value
		{
			get
			{
				if ((null != m_value) && string.IsNullOrEmpty(m_value.Url))
				{
					return null;
				}
				return m_value;
			}
			set
			{
				this.OriginalValue = value;
				m_value = value;
			}
		}

		#endregion //Properties

		#region IPostBackEventHandler Implementation

		public void RaisePostBackEvent(string eventArgument)
		{
			if (!string.IsNullOrEmpty(eventArgument))
			{
				int idx = eventArgument.IndexOf('|');
				if (-1 != idx)
				{
					string cmd = eventArgument.Substring(0, idx);
					string argument = eventArgument.Substring(idx + 1);
					switch (cmd)
					{
						case "upload":
						{
							DeleteTempPicture();
							this.Value = new PictureLiteValue()
							{
								Url = argument,
								CssClass = string.Format("sq-img-{0}", this.PictureField.InternalName)
							};
							break;
						}
						case "remove":
						{
							DeleteTempPicture();
							this.Value = null;
							break;
						}
					}
				}
			}
		}

		#endregion //IPostBackEventHandler Implementation

		#region Overrides

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			if (null == this.PictureField)
			{
				throw new NullReferenceException("PictureField should not be empty.");
			}
		}

		protected override void LoadViewState(object savedState)
		{
			base.LoadViewState(savedState);

			object value = this.ViewState["Value"];
			m_value = (null != value) ? new PictureLiteValue((string)value) : null;
		}

		protected override object SaveViewState()
		{
			this.ViewState["Value"] = (null == this.Value) ? null : this.Value.ToString();
			return base.SaveViewState();
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			SPList list = m_fieldPicture.ParentList;
			SPWeb web = list.ParentWeb;

			string urlUploadPictureDialog = string.Format("/_layouts/Sparqube.PictureLiteField/uploadpicture.aspx?isdlg=1&List={0}&FieldName={1}",
				list.ID, this.PictureField.InternalName, (string)this.ViewState["FileKey"]);
			urlUploadPictureDialog = SPUrlUtility.CombineUrl(web.ServerRelativeUrl, urlUploadPictureDialog);

			string defImageUrl = "/_layouts/images/Sparqube.PictureLiteField/defaultpicture.png";

			ImgPreview.Src = (null == this.Value) ? defImageUrl : this.Value.Url;

			linkUpload.Attributes["onclick"] = string.Format("PictureLite_Upload('{0}', '{1}');return false;",
				SPHttpUtility.EcmaScriptStringLiteralEncode(urlUploadPictureDialog), this.UniqueID);
			linkRemove.Attributes["onclick"] = string.Format("PictureLite_Remove('{0}');return false;", this.UniqueID);
		}

		protected override void Render(HtmlTextWriter writer)
		{
			if (null == this.Value)
			{
				linkRemove.Attributes["disabled"] = "disabled";
				linkRemove.Style[HtmlTextWriterStyle.Color] = "gray";
			}
			base.Render(writer);
		}

		#endregion //Overrides

		#region Implementation

		private void DeleteTempPicture()
		{
			if (null != this.Value)
			{
				if ((null == this.OriginalValue) ||
					!string.Equals(this.OriginalValue.Url, this.Value.Url, StringComparison.InvariantCultureIgnoreCase))
				{
					PictureUploader uploader = new PictureUploader(this.PictureField, SPContext.Current.Web);
					uploader.DeletePicture(this.Value);
				}
			}
		}

		#endregion //Implementation

	}// PictureLiteFieldContent
}
